package com.wcfsy.wechat.wx.um.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;

import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.wcfsy.wechat.wx.exception.ServiceException;
import com.wcfsy.wechat.wx.um.entity.Permission;
import com.wcfsy.wechat.wx.um.entity.TreeNodeVo;
import com.wcfsy.wechat.wx.um.service.IPermissionService;
import com.wcfsy.wechat.wx.util.JsonMessage;

/**
 * 权限树管理
 * 
 * @author yiqiang
 *
 */
@Controller
@RequestMapping("/cms/permistree_manager")
public class PermisTreeManagerController extends AbstractXssDefenderController {
	private static final Logger logger = LoggerFactory
			.getLogger(PermisTreeManagerController.class);

	@Resource
	private IPermissionService permissionService;

	@RequestMapping("/view/page")
	@ResponseBody
	public ModelAndView mainPage() {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("operator/permistree_manager");

		List<Permission> permissions = this.permissionService
				.findByParam(new HashMap<String, Object>());
		List<TreeNodeVo> permisTreeNodeList = new ArrayList<TreeNodeVo>(
				permissions == null ? 0 : permissions.size());
		TreeNodeVo permisTreeNodeVo = null;
		if ((permissions != null) && (!permissions.isEmpty())) {
			for (Permission permission : permissions) {
				permisTreeNodeVo = new TreeNodeVo();
				permisTreeNodeVo.setId(permission.getId() + "");
				permisTreeNodeVo.setParentId(permission.getParentPermisId()
						+ "");
				permisTreeNodeVo.setName(permission.getName());

				permisTreeNodeList.add(permisTreeNodeVo);
			}
		}

		modelAndView.addObject("permisTreeNodeList", permisTreeNodeList);
		try {
			/*
			 * Subject currentUser = SecurityUtils.getSubject(); if (currentUser
			 * != null) modelAndView.addObject("canDrag",
			 * Boolean.valueOf(currentUser
			 * .isPermitted("permistree_manager:update"))); else
			 */
			modelAndView.addObject("canDrag", true);
		} catch (Exception e) {
			modelAndView.addObject("canDrag", Boolean.valueOf(false));
			logger.error("权限树拖拽控制异常，将导致有修改权限的用户无法拖拽权限：" + e.getMessage());
		}
		return modelAndView;
	}

	@RequestMapping("/add")
	@ResponseBody
	public ModelAndView addPermis(@Param("id") String id,
			@Param("name") String name) {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("operator/permistree_manager_add");

		modelAndView.addObject("parentPermisId", id);
		try {
			modelAndView.addObject("parentPermisName",
					URLDecoder.decode(name, "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			logger.debug(name + "新增权限转码异常:" + e.getMessage());
		}

		return modelAndView;
	}

	@RequestMapping("/add/submit")
	@ResponseBody
	public JsonMessage addPermisSubmit(Permission permis) {
		JsonMessage jsonMessage = new JsonMessage();
		if (permis == null) {
			jsonMessage.setSuccess("error");
			jsonMessage.setMessage("新增权限失败,传入的参数为空");
			return jsonMessage;
		}

		try {
			List queryPermis = this.permissionService
					.queryPermisByPermisCode(permis.getCode());
			if ((queryPermis != null) && (!queryPermis.isEmpty())) {
				throw new ServiceException("PER002", "code已经存在");
			}

			if (permis.getParentPermisId() > 0L) {
				Permission parentPermis = this.permissionService.getById(permis
						.getParentPermisId());
				if (parentPermis == null)
					throw new ServiceException("PER003", "上级权限不存在");
			} else {
				permis.setParentPermisId(-1L);
			}

			// user = (User)
			// SecurityManager.getSessionAttribute("SESSION_USER");
			// permis.setCreateId(Integer.valueOf(user != null ? (int) user
			// .getId() : -1));
			permis.setCreateId(1);
			permis.setCreateDate(new Date());
			permis.setId(this.permissionService.add(permis).longValue());
		} catch (ServiceException e) {
			logger.error("新增权限失败:" + permis + " 异常：" + e.getCode() + " "
					+ e.getMsg());
			jsonMessage.setSuccess("error");
			jsonMessage.setMessage("新增权限失败:" + e.getMsg());
			return jsonMessage;
		} catch (Exception e) {
			logger.error("新增权限失败:" + permis + " 异常：" + e.getMessage());
			jsonMessage.setSuccess("error");
			jsonMessage.setMessage("新增权限失败:系统异常");
			return jsonMessage;
		}
		jsonMessage.setSuccess("succeed");
		jsonMessage.setMessage("新增权限成功");
		jsonMessage.setData(permis);
		return jsonMessage;
	}

	@RequestMapping("/delete")
	@ResponseBody
	public JsonMessage deletePermis(@Param("id") long id) {
		JsonMessage json = new JsonMessage();
		try {
			this.permissionService.deleteById(id);
		} catch (ServiceException e) {
			logger.error("删除权限失败，id：" + id + " 异常：" + e.getCode() + " "
					+ e.getMsg());
			json.setSuccess("error");
			json.setMessage("删除权限失败:" + e.getMsg());
			return json;
		} catch (Exception e) {
			logger.error("删除权限失败，id：" + id + " 异常：" + e.getMessage());
			json.setSuccess("error");
			json.setMessage("删除权限失败:系统异常");
			return json;
		}
		json.setSuccess("succeed");
		json.setMessage("删除权限成功");
		return json;
	}

	@RequestMapping("/modify")
	@ResponseBody
	public ModelAndView modifyPermis(@Param("id") long id,
			@Param("parentPermisName") String parentPermisName) {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("operator/permistree_manager_modify");
		try {
			modelAndView.addObject("parentPermisName",
					URLDecoder.decode(parentPermisName, "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			logger.error("修改权限编码转化异常：" + e.getMessage());
		}
		Permission permis = this.permissionService.getById(id);
		if (permis != null) {
			modelAndView.addObject("permis", permis);
		}

		return modelAndView;
	}

	@RequestMapping("/modify/submit")
	@ResponseBody
	public JsonMessage modifyPermisSubmit(Permission permis) {
		JsonMessage json = new JsonMessage();
		if (permis == null) {
			json.setSuccess("error");
			json.setMessage("参数为空，修改权限失败");
			return json;
		}
		try {
			/*
			 * User user = (User) SecurityManager
			 * .getSessionAttribute("SESSION_USER");
			 * permis.setUpdateId(Integer.valueOf(user != null ? (int) user
			 * .getId() : -1));
			 */
			permis.setUpdateId(1);
			permis.setUpdateDate(new Date());
			this.permissionService.update(permis);
		} catch (ServiceException e) {
			logger.error("修改权限失败，Permission：" + permis + " 异常：" + e.getCode()
					+ " " + e.getMsg());
			json.setSuccess("error");
			json.setMessage("修改权限失败:" + e.getMsg());
			return json;
		} catch (Exception e) {
			logger.error("修改权限失败，Permission：" + permis + " 异常："
					+ e.getMessage());
			json.setSuccess("error");
			json.setMessage("修改权限失败:系统异常");
			return json;
		}
		json.setData(permis);
		json.setSuccess("succeed");
		json.setMessage("更新权限成功");
		return json;
	}

}
